package com.wildlife.springboot.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wildlife.springboot.common.Result;
import com.wildlife.springboot.entity.AmphibianFeature;
import com.wildlife.springboot.mapper.service.ImageUploadService;
import com.wildlife.springboot.service.IAmphibianFeatureService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/amphibianFeature")
public class AmphibianFeatureController {

    @Resource
    private IAmphibianFeatureService amphibianFeatureService;

    @Resource
    private ImageUploadService imageUploadService;

    //新增和修改
    @PostMapping
    public Result save(@RequestBody AmphibianFeature amphibianFeature){
        //新增或更新
        return Result.success(amphibianFeatureService.saveOrUpdate(amphibianFeature));
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(amphibianFeatureService.removeById(id));
    }

    @PostMapping ("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids){
        return Result.success(amphibianFeatureService.removeByIds(ids));
    }

    @GetMapping
    public Result findAll() {
        return Result.success(amphibianFeatureService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(amphibianFeatureService.getById(id));
    }

    @GetMapping("/chineseName/{chineseName}")
    public Result findOne(@PathVariable String chineseName) {
        QueryWrapper<AmphibianFeature> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("chinese_name", chineseName);
        return Result.success(amphibianFeatureService.getOne(queryWrapper));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String chineseName
    ) {
        QueryWrapper<AmphibianFeature> queryWrapper = new QueryWrapper<>();
        if (!"".equals(chineseName)) {
            queryWrapper.like("chinese_name", chineseName);
        }
        return Result.success(amphibianFeatureService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    // 导出接口
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<AmphibianFeature> list = amphibianFeatureService.list();
        // 通过工具类创建writer 写出到磁盘路径

        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 自定义标题别名
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("outline", "目");
        writer.addHeaderAlias("section", "科");
        writer.addHeaderAlias("genus", "属");
        writer.addHeaderAlias("chineseName", "种中文名");
        writer.addHeaderAlias("latinName", "种拉丁名");
        writer.addHeaderAlias("discoveryTime", "物种发现时间");
        writer.addHeaderAlias("patternOrigin", "模式产地");
        writer.addHeaderAlias("chineseThreat", "中国受威胁等级");
        writer.addHeaderAlias("iucn", "全球受威胁等级");
        writer.addHeaderAlias("riskFactors", "致危因子");
        writer.addHeaderAlias("chineseEndemicSpecies", "是否中国特有种");
        writer.addHeaderAlias("islandEndemicSpecies", "是否岛屿特有种");
        writer.addHeaderAlias("maleLength", "雄性体长/mm");
        writer.addHeaderAlias("femaleLength", "雌性体长/mm");
        writer.addHeaderAlias("eggCount", "窝卵数");
        writer.addHeaderAlias("eggDiameter", "卵径/mm");
        writer.addHeaderAlias("spawningSite", "产卵地点");
        writer.addHeaderAlias("juvenilesHabitat", "幼体主要生境");
        writer.addHeaderAlias("adultHabitat", "成体微生境");
        writer.addHeaderAlias("activityCycle", "活动模式");
        writer.addHeaderAlias("reproductiveCycle", "生殖周期");
        writer.addHeaderAlias("reproductionTime", "繁殖时间（月份）");
        writer.addHeaderAlias("parentalCare", "亲本照顾");
        writer.addHeaderAlias("fertilizationMethod", "受精方式");
        writer.addHeaderAlias("altitudeRange", "海拔范围/m");
        writer.addHeaderAlias("area", "分布地区");
        writer.addHeaderAlias("distributionProvince", "分布省份数（共34）");
        writer.addHeaderAlias("literatureResources", "物种数据来源");

        writer.write(list, true);

        // 设置浏览器相应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("两栖类特征表", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    // 导入接口
    // reader.addHeaderAlias(): 忽略表头的中文
    @PostMapping("/import")
    public Boolean imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        reader.addHeaderAlias("ID", "id");
        reader.addHeaderAlias("目", "outline");
        reader.addHeaderAlias("科", "section");
        reader.addHeaderAlias("属", "genus");
        reader.addHeaderAlias("种中文名", "chineseName");
        reader.addHeaderAlias("种拉丁名", "latinName");
        reader.addHeaderAlias("物种发现时间", "discoveryTime");
        reader.addHeaderAlias("模式产地", "patternOrigin");
        reader.addHeaderAlias("中国受威胁等级", "chineseThreat");
        reader.addHeaderAlias("全球受威胁等级", "iucn");
        reader.addHeaderAlias("致危因子", "riskFactors");
        reader.addHeaderAlias("是否中国特有种", "chineseEndemicSpecies");
        reader.addHeaderAlias("是否岛屿特有种", "islandEndemicSpecies");
        reader.addHeaderAlias("雄性体长/mm", "maleLength");
        reader.addHeaderAlias("雌性体长/mm", "femaleLength");
        reader.addHeaderAlias("窝卵数", "eggCount");
        reader.addHeaderAlias("卵径/mm", "eggDiameter");
        reader.addHeaderAlias("产卵地点", "spawningSite");
        reader.addHeaderAlias("幼体主要生境", "juvenilesHabitat");
        reader.addHeaderAlias("成体微生境", "adultHabitat");
        reader.addHeaderAlias("活动模式", "activityCycle");
        reader.addHeaderAlias("生殖周期", "reproductiveCycle");
        reader.addHeaderAlias("繁殖时间（月份）", "reproductionTime");
        reader.addHeaderAlias("亲本照顾", "parentalCare");
        reader.addHeaderAlias("受精方式", "fertilizationMethod");
        reader.addHeaderAlias("海拔范围/m", "altitudeRange");
        reader.addHeaderAlias("分布地区", "area");
        reader.addHeaderAlias("分布省份数（共34）", "distributionProvince");
        reader.addHeaderAlias("物种数据来源", "literatureResources");
        List<AmphibianFeature> list = reader.readAll(AmphibianFeature.class);
        amphibianFeatureService.saveBatch(list);
        return true;
    }

    // 上传图片接口
    @PostMapping("/upload")
    public Result uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            String url = imageUploadService.uploadImage(file);
            // 返回相对路径而不是完整的本地文件路径
            return Result.success(url);
        } catch (Exception e) {
            return Result.fail("上传失败");
        }
    }
}
